const path = require('path');
const CopyPlugin = require('copy-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const ZipPlugin = require('zip-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {
  entry: {
    background: './src/background.ts',
    content: './src/content.ts',
    sidebar: './src/sidebar.ts',
    styles: './src/styles.scss', // 新增入口：把 SCSS 编译为独立 CSS
  },
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist'),
    clean: true,
  },
  mode: 'production',
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
      {
        test: /\.s[ac]ss$/i,
        use: [
          MiniCssExtractPlugin.loader, // 抽取成单独的 CSS 文件
          'css-loader',
          'sass-loader',
        ],
      },
    ],
  },
  resolve: {
    extensions: ['.ts', '.js'],
  },
  optimization: {
    minimize: true,
    minimizer: [
      new TerserPlugin({
        terserOptions: {
          mangle: false,
          keep_classnames: true,
          keep_fnames: true,
          compress: {
            drop_console: false,
            reduce_vars: true,
          },
          format: {
            comments: 'some',
            beautify: false,
          },
        },
        extractComments: false,
      }),
    ],
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: 'styles.css', // 输出成 dist/styles.css
    }),
    new CopyPlugin({
      patterns: [
        { from: 'src/sidebar.html', to: 'sidebar.html' },
        { from: 'manifest.json', to: '' },
        { from: 'src/icons', to: 'icons' },
        { from: 'src/jquery-3.6.4.min.js', to: '' },
        { from: 'src/xlsx.full.min.js', to: '' },
      ],
    }),
    new ZipPlugin({
      filename: 'dist.zip',
      path: path.resolve(__dirname),
      fileOptions: {
        mtime: new Date(),
        mode: 0o100664,
        compress: true,
        forceZip64Format: false,
      },
      zipOptions: {
        forceZip64Format: false,
      },
    }),
  ],
};
